package com.iraeta.service.wx.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iraeta.entity.type.WxMessageStatus;
import com.iraeta.entity.wx.Wxtextmessage;
import com.iraeta.mapper.wx.WxtextmessageMapper;
import com.iraeta.service.sys.impl.WeiXinService;
import com.iraeta.service.wx.IWxtextmessageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class WxtextmessageServiceImpl extends ServiceImpl<WxtextmessageMapper, Wxtextmessage> implements IWxtextmessageService {
    @Resource
    WeiXinService weiXinService;

    @Override
    public List<Wxtextmessage> listUnSendMeg() {
        QueryWrapper<Wxtextmessage> qw = new QueryWrapper<>();
        qw.eq("status_id", WxMessageStatus.unSend);
        qw.orderByDesc("id");
        return baseMapper.selectList(qw);
    }

    @Override
    public void loopSendWxTextMsgTask() {
        List<Wxtextmessage> unSendList = this.listUnSendMeg();
        for (Wxtextmessage wxtextmessage : unSendList) {
            String msg = weiXinService.setWxUserTextMessage(wxtextmessage);
            if(StrUtil.isEmpty(msg)){
                wxtextmessage.setStatusId(WxMessageStatus.sendSuccess);
            }else{
                wxtextmessage.setStatusId(WxMessageStatus.sendFail);
                wxtextmessage.setErrorMsg(msg);
            }
            baseMapper.updateById(wxtextmessage);
        }
    }
}
